package com.hczt.fire.server.common.exception.global;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 异常统一处理
 * @author sundonghe
 *
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
	private static final Integer ERROR_CODE = -1;
	private static final String ERROR_MSG = "系统发生异常，请与管理员联系";
	private static final String PARAM_ERROR_MSG = "参数传值异常，请检查";
	
	@ExceptionHandler(value={BizException.class, Exception.class})
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public ErrorMsg<String> jsonErrorHandler(HttpServletRequest request, Throwable e) {
		log.error("异常被捕获，执行【{}】时发生异常",request.getRequestURL().toString(),e);
		ErrorMsg<String> errorInfo = new ErrorMsg<>();
		errorInfo.setCode(ERROR_CODE);
		errorInfo.setMessage(ERROR_MSG);
		errorInfo.setUrl(request.getRequestURL().toString());
		errorInfo.setData(e.getMessage());
		return errorInfo;
	}

	@ExceptionHandler(value={BindException.class, MethodArgumentNotValidException.class})
	@ResponseBody
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ErrorMsg<List<String>> jsonErrorHandler(HttpServletRequest request, BindException exception) {
		log.error("异常被捕获，执行【{}】时发生异常",request.getRequestURL().toString(),exception);
		List<String> errorList = exception.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
		ErrorMsg<List<String>> errorInfo = new ErrorMsg<>();
		errorInfo.setCode(ERROR_CODE);
		errorInfo.setMessage(PARAM_ERROR_MSG);
		errorInfo.setUrl(request.getRequestURL().toString());
		errorInfo.setData(errorList);
		return errorInfo;
	}

	@ExceptionHandler(value=ConstraintViolationException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ErrorMsg<List<String>> jsonErrorHandler(HttpServletRequest request, ConstraintViolationException exception) {
		log.error("异常被捕获，执行【{}】时发生异常",request.getRequestURL().toString(),exception);
		List<String> errorList = exception.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
		ErrorMsg<List<String>> errorInfo = new ErrorMsg<>();
		errorInfo.setCode(ERROR_CODE);
		errorInfo.setMessage(PARAM_ERROR_MSG);
		errorInfo.setUrl(request.getRequestURL().toString());
		errorInfo.setData(errorList);
		return errorInfo;
	}
}